#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''


from pycommon import TBaseProtocol
import GameFactory
import logging
import GameParse
import GameManager
import CenterBuild

GAME_STATE_INIT               = 0
GAME_STATE_LOGINED            = 1
GAME_STATE_TO_CLOSE           = 2

class GameSrv(TBaseProtocol.TBaseProtocol):

    def __init__(self, pid, addr):
        TBaseProtocol.TBaseProtocol.__init__(self)
        self.__id = pid
        self.__addr = addr
        self.__ip = addr.host.decode('utf-8')
        self.__sid = 0
        self.__sip = 0
        self.__sport = 0
        self.state = GAME_STATE_INIT 
        
    def getId(self):
        return self.__id
    
    def getSId(self):
        return self.__sid

    def getSIp(self):
        return self.__sip

    def getSPort(self):
        return self.__sport
    
    def getIp(self):
        return self.__ip

    def getState(self):
        return self.state
    
    def packetReceived(self, cmd, pkt):
        if self.state == GAME_STATE_TO_CLOSE:
            return
        try:
            GameParse.parse(self, cmd, pkt)
        except Exception:
            logging.exception(u"GameParse.parse(), cmd=%d" % cmd)
        
    def sendPacket(self, pkt):
        if not self.isConnected():
            logging.warn(u"sendPacket() not connected")
            return
        TBaseProtocol.TBaseProtocol.sendPacket(self, pkt)
    
    def connectionMade(self):
        logging.debug(u"GameSrv.connectionMade() ip=%s", self.__ip) 
        TBaseProtocol.TBaseProtocol.reset(self)
   
    def connectionLost(self, reason):
        logging.debug(u"GameSrv.connectionLost %s", reason)
        self.state = GAME_STATE_TO_CLOSE 
        sid = self.getSId()
        if sid > 0:
            count = GameFactory.instance.getGameSrvCountBySid(sid)
            if count == 1:
                GameManager.instance.gameLogout(sid)
            else:
                logging.warn(u"sid=%d Game 存在不正常退出情况!",sid)
        logging.debug(u"GameFactory.instance.removeProtocol")
        GameFactory.instance.removeProtocol(self)
        
    def onLogin(self, sid,sip,sport):
        self.__sid = sid 
        if len(sip) == 0:
            self.__sip = self.__ip
        else:
            self.__sip = sip
        self.__sport = sport
        self.state = GAME_STATE_LOGINED     

    def transPkt2Game(self,uid,pkt):
        self.sendPacket(CenterBuild.transPkt2Game(uid,pkt))

if __name__ == "__main__":
    pass